#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from sqlalchemy import create_engine
from werkzeug.utils import import_string

from blog.extenstion import db

__author__ = 'Tim Yao'

from flask import Flask
from config import config

__all__ = ["create_app"]
# db = SQLAlchemy()
engine = None

DEFAULT_BLUEPRINTS = (
    ("blog.api", "api", "/api"),
    ("blog.user", "user", "/user"),
)


def create_app(config_name, blueprints=None):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    if blueprints is None:
        blueprints = DEFAULT_BLUEPRINTS

    configure_blueprints(app, blueprints)
    configure_extensions(app)
    app.run(host='0.0.0.0', port=8080)
    return app


def configure_extensions(app):
    db.init_app(app)


def configure_blueprints(app, blueprints):
    for blueprint in blueprints:
        _register_blueprint(app, blueprint)


def _register_blueprint(app, blueprint):
    if len(blueprint) is not 3:
        raise SyntaxError('BLUEPRINTS Invalid syntax!!!')
    path, name, prefix = blueprint

    try:
        packet = import_string(path + ".views")
    except Exception as msg:
        raise ImportError('import blueprint fail!!! %s' % msg)
    modules_name = getattr(packet, name, None)
    if not modules_name:
        app.logger.error("import blueprint %s from %s failed!\n" %
                         (name, packet + ".views"))
        raise ImportError("import blueprint %s from %s failed!\n" %
                          (name, packet + ".views"))
    if prefix:
        app.register_blueprint(modules_name, url_prefix=prefix)
    else:
        app.register_blueprint(modules_name)
